// pages/me/setting/setting.js
import Utils from '../../../utils/utils';
import {
  PayHttp
} from '../../../api/pay.js'
import User from '../../../utils/user';
const payModel = new PayHttp();
Page({
  /**
   * 页面的初始数据
   */
  type:1,
  isLoading:false,
  data: {
    version:Utils.version,
    payment: '3',
    paymentVal: '1',
    paymentMoney: 50,
    checkedIcon: {
      active: '/images/icon/icon_check_active.png',
      normal: '/images/icon/icon_check_inactive.png',
      normalEmpty: '/images/icon/icon_check_inactive_empty.png'
    },
    chargeProtocol: {
      "name": "会员充值规则",
      "path": Utils.pageUrl + "/copyright/charge_protocol.html",
      "downUrl": "",
      "version": 1
    }
  },
  initPage: function(options) {
    let app = getApp();
    if(app.globalData.pageConfig.chargeProtocol){
      this.setData({
        chargeProtocol:app.globalData.pageConfig.chargeProtocol
      });
    }
    if(options.hasOwnProperty('type')){
      this.type = Utils.fixInt(options['type']);
    }
  },
  // 关闭
  onClose () {
    this.triggerEvent('close')
  },
  // 选择充值金额
  onSelectAmount (event) {
    const { type, money } = event.currentTarget.dataset
    this.setData({ paymentVal: type, paymentMoney: money });
  },
  // 选择支付方式
  onSelectPayment (event) {
    const { name } = event.currentTarget.dataset;
    this.setData({ payment: name });
  },
  // 确认充值
  onConfirmRecharge () {
    let self = this;
    Utils.loading('加载中');
    if(self.isLoading === true){
      return false;
    }
    self.isLoading = true;
    payModel.memberPay({
      "money_pay": this.data.paymentMoney * 100, //要充值的金额，单位分
      "soft_id": 2, // 软件id APP填写0 巷友小程序填写2
      "pay_type": 3, //支付类型  2:支付宝 3：微信 4:会员卡
    }).then((res) => {
      self.isLoading = false;
      setTimeout(function () {
        Utils.closeLoading();
      },100);
      wx.requestPayment({
        timeStamp: res.mini.timeStamp,
        nonceStr: res.mini.nonceStr,
        package: res.mini.package,
        signType: res.mini.signType,
        paySign: res.mini.paySign,
        success (res) {
          User.getUserInfoByNet();
          if(self.type === 2){
            Utils.msg('充值成功');
            setTimeout(function () {
              wx.navigateBack();
            },400)
          }else{
            setTimeout(function () {
              utils.toPage('/pages/me/notify/index?type=5',false,true);
            },200);
          }
        },
        fail (res) {
          if(res.errMsg === 'requestPayment:fail cancel'){
            Utils.msg('您取消了支付！');
          }else{
            Utils.msg('充值失败');
          }
        }
      })
    }).catch(()=>{
      self.isLoading = false;
    })
  }
});
